package angry.courses.beans;

import javax.ejb.Stateless;
import javax.ejb.Remote;
import javax.ejb.EJB;

import angry.courses.entities.CourseEntity;
import angry.courses.entities.StudentEntity;
import angry.courses.entities.RelationEntity;

import java.util.List;
import java.util.ArrayList;

@Stateless(mappedName="angry.courses.beans.RegisterBean")
@Remote
public class RegisterBean implements Register {
	@EJB
	private CourseDAO courseDAO;
	@EJB
	private StudentDAO studentDAO;
	@EJB
	private RelationDAO relationDAO;

	public CourseEntity getCourse(String name) {
		return courseDAO.retrieve(name);
	}
	
	public StudentEntity createStudent(String name, String regNr, int year) {
		StudentEntity newStudent = new StudentEntity(name, regNr, year);
		studentDAO.create(newStudent);
		return newStudent;
	}
	
	public void register(CourseEntity course, StudentEntity student) {
		relationDAO.create(course.getID(), student.getID());
	}
	
	public List<String> getCourseNamesForStudent(StudentEntity student, int sem) {
		List<String> courseNames = new ArrayList<String>();
		List<Integer> courseIDs =
			relationDAO.getCourseIdsForStudent(student.getID());
			
		for (int cid : courseIDs) {
			CourseEntity course = courseDAO.retrieve(cid);
			if (course.getSemester() == sem) {
				courseNames.add(course.getName());
			}
		}
		return courseNames;
	}
	
	public void deleteCoursesForStudent(StudentEntity student) {
		List<RelationEntity> relations =
			relationDAO.getRelationsForStudent(student.getID());
		for (RelationEntity relation : relations) {
			relationDAO.remove(relation);
		}
	}
	
	public void deleteRelationsForCourse(CourseEntity course) {
		List<RelationEntity> relations =
			relationDAO.getRelationsForCourse(course.getID());
		for (RelationEntity relation : relations) {
			relationDAO.remove(relation);
		}
	}
	
	public void modifyStudent(StudentEntity student) {
		studentDAO.modify(student);
	}
}
